﻿(function ($) {
    $.fn.AutoComplete = function (url, option) {

        var me = this;
        var strKey = $(me).val();

        var strKeyBak = "";
        var strKeyValue = "";
        var isShow = false;
        var doption = {
            divid: "autocomplete",      //div ID
            overselect: true,               //是否要屏蔽select
            iwidth: '0px',                    //下拉框的宽度
            iLengthLower: 1,              //当表单的长度大于iLengthLower小于iLengthUpper时才开始执行搜索
            iLengthUpper: 50,
            strPara: "Keyword",         //变量名称
            zIndex: 1,                        //提示框的Z-INDEX值
            hasscroll: 0,                     //是否出现滚动条0无1有
            hasclose: 1,                     //是否拥有关闭窗口
            isemptyMsg: "请输入内容",
            desfun: function (retext, revalue) { },
            pagesize: 10//分页大小
        };


        $.extend(doption, option);
        var iLengthLower = doption.iLengthLower;
        var iLengthUpper = doption.iLengthUpper;
        var strPara = doption.strPara;

        //分页使用 add by wyq 20100219
        var pagesize = doption.pagesize;
        var pageindex = 1; //当前页签
        var pagedata = null;
        var Pagesdata = null;

        if ($("#" + doption.divid).length < 1) { $("body").append("<div id='" + doption.divid + "'></div>"); }

        $("#" + doption.divid).hide();


        //获取选中的值
        function getselectvalue() {
            strKeyBak = $("#" + doption.divid + " ul .selected .keyname").text(); //为click事件增加处理
            strKeyValue = $("#" + doption.divid + " ul .selected .keyname").attr("value");
            if (typeof (strKeyValue) == "undefined") {
                strKeyValue = "none";
            }

            //doption.desfun(strKeyBak, strKeyValue);
            if (strKeyBak.length > 0) {
                $(me).val(strKeyBak);
                $(me).attr("hiddenvalue", strKeyValue);

                doption.desfun(strKeyBak, strKeyValue);
                floorHide();
            };
        }

        $(me).mousedown(function () { Onclick(); });
        $(me).keyup(function (e) { keysearch(e.keyCode); });
        $(me).keydown(function (e) { LineSelect(e.keyCode); });
        $(me).bind("blur", function () { getselectvalue(); });


        var encode = function (v) {//如果包含中文就escape,避免重复escape)
            return escape(v).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
        }

        function floorHide() {
            $("#" + doption.divid).hide(); //.html("");
            strKey = "";
            isShow = false;
        }

        function floorShow() {
            var p = $(me).offset();
            var w = (doption.iwidth == "0px") ? $(me).width() + 3 : doption.iwidth;

            $("#" + doption.divid).css({
                'z-index': doption.zIndex,
                width: w,
                top: parseInt(p.top + $(me).outerHeight()) + "px",
                left: parseInt(p.left) + "px"
            }).show().addClass("autocomplete");

            strKey = "";
            isShow = true;
        }

        //显示
        function showdiv() {//显示
            $("#" + doption.divid).show();
            strKey = "";
            isShow = true;

        }
        //隐藏
        function hidediv() {//隐藏
            floorHide();
        }

        function Onclick() {
            var strKeyNow = $(me).val();

            $.ajax({
                type: "POST",
                dataType: "json",
                cache: false,
                url: url,
                data: strPara != "" ? strPara + "=" + encode(strKeyNow) : "",
                success: function (json) {
                    if (json != undefined) {
                        json = json.keylist;
                        Pagesdata = json
                        if (json.length > 0) {
                            OutputHtml();
                        }
                    }
                }
            });
        }


        function keysearch(code) {//开始搜索
            var strKeyNow = $(me).val();
            $(me).attr("hiddenvalue", ""); //设置隐藏值
            if (code == 38 || code == 40 || code == 13 || code == 27 || code == 9) return;


            //TAB/回车、ESC、向上、向下
            if ((strKey == "" || strKeyNow != strKey) && strKeyNow.length >= iLengthLower && strKeyNow.length <= iLengthUpper) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    cache: false,
                    url: url,
                    data: strPara != "" ? strPara + "=" + encode(strKeyNow) : "",
                    success: function (json) {
                        if (json != undefined) {
                            json = json.keylist;
                            Pagesdata = json
                            if (json.length > 0) {
                                OutputHtml();
                            }
                        }
                    }
                });

                strKey = $(me).val();
            }
            if (strKey.length == 0 || strKey.length <= iLengthLower || strKey.length >= iLengthUpper) floorHide();
        }

        function OutputHtml() {
            var strContent = "<ul>";

            if (Pagesdata.length > 0) {
                //分页
                pagedata = Pagesdata; //给pagedata赋值;
                var Pages = Math.floor((pagedata.length - 1) / pagesize) + 1;
                if (pageindex < 1) pageindex = 1;  //如果当前页码小于1
                if (pageindex > Pages) pageindex = Pages; //如果当前页码大于总数
                var Temp = "";
                var BeginNO = (pageindex - 1) * pagesize + 1; //开始编号
                var EndNO = pageindex * pagesize; //结束编号
                if (EndNO > pagedata.length) EndNO = pagedata.length;
                if (EndNO == 0) BeginNO = 0;
                if (!(pageindex <= Pages)) pageindex = Pages;


                if (pageindex > 1 && pageindex != 1) {
                    var prepageindex = parseInt(pageindex) - 1;
                    Temp = "<li class='pages'><a href='javascript:void(0)' onclick=javascript:jQuery('#" + $(me).attr("id") + "').gotopage(1,'" + $(me).attr("id") + "'); title='首页'>«</a><a href='javascript:void(0)'  onclick=jQuery('#" + $(me).attr("id") + "').gotopage(" + prepageindex + ",'" + $(me).attr("id") + "')   title='前一页'>‹</a>&nbsp;";
                }else {
                    Temp = "<li class='pages'><a disabled title='首页'>«</a><a disabled title='前一页'>‹</a>";
                };

                if (pageindex != Pages) {
                    var nextpageindex = parseInt(pageindex) + 1;

                    Temp += "<a title='后一页' href='javascript:void(0)'  onclick=javascript:jQuery('#" + $(me).attr("id") + "').gotopage(" + nextpageindex + ",'" + $(me).attr("id") + "')  >›</a><a href='javascript:void(0)' onclick=jQuery('#" + $(me).attr("id") + "').gotopage(" + Pages + ",'" + $(me).attr("id") + "') title='末页'>»</a>";

                    if (doption.hasclose == 1) {//是否显示关闭
                        Temp += "<span class=\"close\"title='关闭'>关闭</span>";
                    }
                    Temp += "</li>";
                }else {
                    Temp += "<a disabled title='后一页'>›</a><a disabled title='末页'>»</a>";
                    if (doption.hasclose == 1) {//是否显示关闭
                        Temp += "<span class=\"close\" title='关闭'>关闭</span>";
                    }
                    Temp += "</li>";
                }


                for (var i = BeginNO - 1; i < EndNO; i++) {
                    var tempdata = pagedata[i];
                    if (tempdata.keyname.length > 0) {//如果
                        if (typeof (tempdata.keyvalue) != "undefined") {
                            strContent += '<li class="keyinfo" title="' + tempdata.keyname + '"><span class="keyname" value="' + tempdata.keyvalue + '">' + tempdata.keyname + '</span>';
                        }else {
                            strContent += '<li class="keyinfo" title="' + tempdata.keyname + '"><span class="keyname" value="none">' + tempdata.keyname + '</span>';
                        }
                        try {
                            if (tempdata.keyextend.length > 0) { strContent += '<span class="keyextend" title="' + tempdata.keyextend + '">' + tempdata.keyextend + '</span>'; }
                        } catch (E) { };
                        strContent += '</li>';
                    };
                }
            } else {
                //没有搜索数据
                strContent += '<li class="keyinfo"><span class="keyname">没有任何数据</span>';
            }

            strContent += Temp;

            strContent += '</ul>';
            if (doption.overselect == true) {//是否要屏蔽select
                strContent += '<iframe id="autocompleteifr" style="position: absolute; z-index: -1; width: 100%; height:100%; top: 0;left: 0; scrolling: no;" frameborder="0" src="about:blank"></iframe>';
                $("#" + doption.divid).html(strContent);
                $("#autocompleteifr").css('height', $("#" + doption.divid).height() + 'px');
            } else {
                $("#" + doption.divid).html(strContent);
            }

            $("#" + doption.divid + " .keyinfo").mouseover(function () { $("#" + doption.divid + " .selected").removeClass("selected"); $(this).removeClass("unselected").addClass("selected"); }).mouseout(function () { $(this).removeClass("selected").addClass("unselected"); }).click(function () { getselectvalue(); });

            if (doption.hasclose == 1) {//是否显示关闭 给关闭添加事件
                $("#" + doption.divid + " .close").mousedown(function () { floorHide(); });
            }
            floorShow();
        }


        function LineSelect(code) {
            var strKey = "";
            var strkeyvalue = "";
            if (code == 27) {//ESC键
                floorHide();
            }; //回车键、ESC键            
            if (!isShow) return;
            ObjSelected = $("#" + doption.divid + " ul .selected");
            if (ObjSelected.length > 0) {//如果已经有选定
                //alert('dasfdas');
                if (code == 38) {	//向上键
                    if (ObjSelected.prev().text() != "") {	//如果不是第一个数据
                        ObjSelected.removeClass("selected").addClass("unselected").prev().removeClass("unselected").addClass("selected");
                        $(me).val($("#" + doption.divid + " ul .selected .keyname").text());

                        $(me).attr("hiddenvalue", $("#" + doption.divid + " ul .selected .keyname").attr("value")); //设置隐藏值
                    } else {
                        ObjSelected.removeClass("selected").addClass("unselected");
                        $("#" + doption.divid + " .keyinfo:last").removeClass("unselected").addClass("selected");
                        $(me).val($("#" + doption.divid + " ul .selected .keyname").text());
                    }
                } else if (code == 40) {	//向下键
                    if (ObjSelected.next().text() != "") {	//如果不是第一个数据
                        ObjSelected.removeClass("selected").addClass("unselected").next().removeClass("unselected").addClass("selected");
                        $(me).val($("#" + doption.divid + " ul .selected .keyname").text());
                        $(me).attr("hiddenvalue", $("#" + doption.divid + " ul .selected .keyname").attr("value")); //设置隐藏值
                    } else {
                        ObjSelected.removeClass("selected").addClass("unselected");
                        $("#" + doption.divid + ".keyinfo:first").removeClass("unselected").addClass("selected");
                        $(me).val($("#" + doption.divid + " ul .selected .keyname").text());
                        $(me).attr("hiddenvalue", $("#" + doption.divid + " ul .selected .keyname").attr("value")); //设置隐藏值
                    }
                }
            } else if (code == 38) {
                $("#" + doption.divid + " .keyinfo:last").removeClass("unselected").addClass("selected");
                $(me).val($("#" + doption.divid + " .keyinfo:last .keyname").text());
                $(me).attr("hiddenvalue", $("#" + doption.divid + " .keyinfo:last .keyname").attr("value")); //设置隐藏值
            } else if (code == 40) {
                $("#" + doption.divid + " .keyinfo:first").removeClass("unselected").addClass("selected");
                $(me).val($("#" + doption.divid + " .keyinfo:first .keyname").text());
                $(me).attr("hiddenvalue", $("#" + doption.divid + " .keyinfo:last .keyname").attr("value")); //设置隐藏值
            }


            if (code == 13) {//回车事件
                if (ObjSelected.length > 0) {
                    $(me).val($("#" + doption.divid + " ul .selected .keyname").text());
                    $(me).attr("hiddenvalue", $("#" + doption.divid + " ul .selected .keyname").attr("value"));
                } else {
                    $("#" + doption.divid + " .keyinfo:first").removeClass("unselected").addClass("selected");
                    $(me).val($("#" + doption.divid + " .keyinfo:first .keyname").text());
                    $(me).attr("hiddenvalue", $("#" + doption.divid + " .keyinfo:last .keyname").attr("value"));
                }
                strKey = $(me).val();
                strkeyvalue = $(me).attr("hiddenvalue");
                if (strKey.indexOf("没有任何数据") > -1) {
                    doption.desfun(strKey, strkeyvalue);
                } else {
                    doption.desfun(strKey, strkeyvalue);
                }

                floorHide();
            };
        }

        $(me)[0].t = {
            OutputHtml: function (index) {
                pageindex = index;
                OutputHtml();
            },
            showdiv: function () {
                showdiv();
            },
            hidediv: function () {
                hidediv();
            }
        };
        //return $(me);
    }

    $.fn.gotopage = function (pageindex, id) {
        var me = $("#" + id);
        if (me[0].t) {
            me[0].t.OutputHtml(pageindex);
        }
    }
    $.fn.showdiv = function (id) {
        var me = $("#" + id);
        if (me[0].t) {
            me[0].t.showdiv();
        }
    }
    $.fn.hidediv = function (id) {
        var me = $("#" + id);
        if (me[0].t) {
            me[0].t.showdiv();
        }
    }
})(jQuery);